import os
import re
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import urllib.request
import hashlib
import base64
import hmac
import time
import requests
import json
import socket


dingUrl = 'https://oapi.dingtalk.com/robot/send?access_token=a1c00bb50002d323b2cb4959e864793af68a8546c034a3591c56d61988e020c5'
secret = "SECd0f97a21b21bca661857d07b3568eee82e9ec214774141369db7c4fbfcea712c"
driver_path = "C:/Users/Administrator/AppData/Local/Programs/Python/Python311/chromedriver.exe"


def check_chrome_driver():
    ip = get_host_ip()
    print("开始进行chrome和chromdriver检测:"+ip)        
    try:
        driver = webdriver.Chrome(executable_path=driver_path)
        driver.get("http://baidu.com")
    except Exception as e:
        reg = "Current browser version is.+with"
        try:
            chrome_version =re.search(reg, str(e)).group().replace("Current browser version is ", "").replace(" with","")
        except Exception as e:
            print("该路径下找不到chromedriver："+driver_path)
            sendDingV1("","", ip,driver_path)
            return
        print(chrome_version)
        chrome_driver_version = getChromeDriverVersion(driver_path)
        print(chrome_driver_version)
        sendDing(chrome_version,chrome_driver_version, ip,driver_path)
    print("chrome和chromdriver检测完成")        

def getChromeDriverVersion(path):
    outstd2 = os.popen(path+' --version').read()
    try:
        version = outstd2.split(' ')[1]
        version = ".".join(version.split(".")[:-1])
        return version
    except Exception as e:
        return "0.0.0"

def sendDing(chrome_version,chrome_driver_version,ip,driver_path):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc,digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    webUrl = dingUrl + "&timestamp="+timestamp+"&sign="+sign
    print(webUrl)
    text =  "### <font face=‘华云彩绘’ color=#DC143C >chrome driver</font> 运行异常\n#### chrome版本：<font face=‘华云彩绘’ color=#DC143C >{0}</font> \n#### chrome driver 版本：<font face=‘华云彩绘’ color=#DC143C >{1}</font> \n#### 服务器ip: <font face=‘华云彩绘’ color=#DC143C >{2}</font> \n#### chrome driver路径：<font face=‘华云彩绘’ color=#50a14f >{3} </font>\n".format(chrome_version,chrome_driver_version, ip,driver_path)
    my_data = {
        "msgtype": "markdown",
        "markdown": {"title": "chrome driver 运行监控",
                     "text": text
                     },
        "at": {

            "isAtAll": False
        }
    }

    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    sendData = json.dumps(my_data)  # 将字典类型数据转化为json格式
    # sendDatas = sendData.encode("utf-8")
    # 发送请求
    request = requests.post(url=webUrl, data=sendData, headers=header)
    # 将请求发回的数据构建成为文件格式
    # opener = urllib.request.urlopen(request)
    print(request.text)


def sendDingV1(chrome_version,chrome_driver_version,ip,driver_path):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc,digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    webUrl = dingUrl + "&timestamp="+timestamp+"&sign="+sign
    print(webUrl)
    text =  "### <font face=‘华云彩绘’ color=#DC143C >chrome driver 路径有误</font>\n#### 服务器ip: <font face=‘华云彩绘’ color=#DC143C >{2}</font> \n#### chrome driver路径：<font face=‘华云彩绘’ color=#50a14f >{3} </font>\n".format(chrome_version,chrome_driver_version, ip,driver_path)
    my_data = {
        "msgtype": "markdown",
        "markdown": {"title": "chrome driver 运行监控",
                     "text": text
                     },
        "at": {

            "isAtAll": False
        }
    }

    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    sendData = json.dumps(my_data)  # 将字典类型数据转化为json格式
    # sendDatas = sendData.encode("utf-8")
    # 发送请求
    request = requests.post(url=webUrl, data=sendData, headers=header)
    # 将请求发回的数据构建成为文件格式
    # opener = urllib.request.urlopen(request)
    print(request.text)
    
def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()

    return ip
            
check_chrome_driver()
